<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue';
import {
  Delete
} from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
const md = new MarkdownIt()
import 'md-editor-v3/lib/style.css';
import {AskWithKnowledge} from "@/service/chat.ts";
import {GeneratorId} from "@/utils/utils.ts";

// 定义聊天对象接口
interface ChatObject {
  id: number;
  name: string;
  avatar: string;
  color: string;
}

// 定义消息接口
interface Message {
  id: number;
  text: string;
  sender: 'user' | 'ai';
  senderName: string;
  avatar: string;
  time: Date;
}

// 响应式数据
const inputText = ref<string>('');
const messages = ref<Message[]>([]);
const isTyping = ref<boolean>(false);
const inputWarning = ref<string>('');
const showChatObjects = ref<boolean>(false);
const chatId = ref();

// 预设聊天对象
const chatObjects = ref<ChatObject[]>([
  { id: 0, name: '阿米娅', avatar: 'icon-yanjing_yincang_o', color: 'linear-gradient(135deg, #667eea, #764ba2)' },
  { id: 1, name: '三月七', avatar: 'fas fa-code', color: 'linear-gradient(135deg, #f093fb, #f5576c)' },
  { id: 2, name: '镜流', avatar: 'fas fa-language', color: 'linear-gradient(135deg, #4facfe, #00f2fe)' },
]);

const currentChatObject = ref<ChatObject>(chatObjects.value[0]);
// 计算属性
const isValidInput = computed(() => {
  return inputText.value.trim().length > 0;
});

// 格式化时间
const formatTime = (date: Date): string => {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 处理输入
const handleInput = (): void => {
  autoResize();
  inputWarning.value = '';
};

// 切换聊天对象显示
const toggleChatObjects = (): void => {
  showChatObjects.value = !showChatObjects.value;
};

// 选择聊天对象
const selectChatObject = (obj: ChatObject): void => {
  currentChatObject.value = obj;
  showChatObjects.value = false;

  // 添加系统消息
  const systemMessage: Message = {
    id: Date.now(),
    text: `已切换到${obj.name}，请问有什么可以帮助您的？`,
    sender: 'ai',
    senderName: obj.name,
    avatar: obj.avatar,
    time: new Date()
  };
  messages.value.push(systemMessage);
  scrollToBottom();
};

// 发送消息
const sendMessage = async () => {
  if (!isValidInput.value) {
    if (inputText.value.trim().length === 0) {
      inputWarning.value = '请输入内容';
    }
    return;
  }

  // 添加用户消息
  const userMessage: Message = {
    id: Date.now(),
    text: inputText.value,
    sender: 'user',
    senderName: '您',
    avatar: 'fas fa-user',
    time: new Date()
  };

  messages.value.push(userMessage);
  const {data} = await AskWithKnowledge({
    code:currentChatObject.value.id,
    question: userMessage.text,
    conversationId:chatId.value.toString(),
    useKnowledgeBase:true,
  })
  inputText.value = '';
  inputWarning.value = '';
  autoResize();

  // 滚动到底部
  scrollToBottom();

  // 模拟AI回复
  isTyping.value = true;
  scrollToBottom();

  setTimeout(() => {
    const aiMessage: Message = {
      id: Date.now() + 1,
      text: data.answer,
      sender: 'ai',
      senderName: currentChatObject.value.name,
      avatar: currentChatObject.value.avatar,
      time: new Date()
    };
    messages.value.push(aiMessage);
    isTyping.value = false;

    // 滚动到底部
    scrollToBottom();
  }, 1500);
};

// 清空消息
const clearMessages = (): void => {
  messages.value = [];
  inputText.value = '';
  inputWarning.value = '';
  autoResize();
};

// 滚动到底部
const scrollToBottom = (): void => {
  nextTick(() => {
    const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
    if (messagesContainer) {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
  });
};

// 自动调整输入框高度
const autoResize = (): void => {
  nextTick(() => {
    const textarea = document.querySelector('.chat-input textarea') as HTMLTextAreaElement;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = textarea.scrollHeight + 'px';
    }
  });
};

// 生命周期
onMounted(() => {
  scrollToBottom();

  chatId.value = GeneratorId();

  // 点击其他地方关闭聊天对象选择器
  document.addEventListener('click', (e) => {
    const selector = document.querySelector('.chat-object-selector') as HTMLElement;
    if (selector && !selector.contains(e.target as Node)) {
      showChatObjects.value = false;
    }
  });
});
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>{{ currentChatObject.name }}</h1>
      <div class="chat-status">
        <div class="status-indicator"></div>
        <span>在线</span>
      </div>
    </div>

    <div class="chat-messages">
      <div v-if="messages.length === 0" class="empty-state">
        <i class="fas fa-comments"></i>
        <h3>开始与AI对话</h3>
        <p>选择聊天对象并输入您的问题或想法，AI助手将为您提供帮助。</p>
      </div>

      <div v-for="message in messages" :key="message.id" :class="['message', message.sender]">
        <div class="avatar">
          <i :class="message.avatar"></i>
        </div>
        <div class="message-content">
          <div class="message-header">
            <div class="message-sender">{{ message.senderName }}</div>
          </div>
          <div class="message-text" v-html="md.render(message.text)"></div>
          <div class="message-time">{{ formatTime(message.time) }}</div>
        </div>
      </div>

      <div v-if="isTyping" class="message ai">
        <div class="avatar">
          <i :class="currentChatObject.avatar"></i>
        </div>
        <div class="typing-indicator">
          <div class="typing-dots">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div class="chat-object-selector" @click="toggleChatObjects">
        <div class="chat-object-avatar">
          <i :class="currentChatObject.avatar"></i>
        </div>
        <div class="chat-object-name">{{ currentChatObject.name }}</div>
        <div class="chat-objects-dropdown" :class="{ active: showChatObjects }">
          <div
              v-for="obj in chatObjects"
              :key="obj.id"
              :class="['chat-object-option', { active: obj.id === currentChatObject.id }]"
              @click.stop="selectChatObject(obj)"
          >
            <div class="avatar" :style="{ background: obj.color }">
              <i :class="obj.avatar"></i>
            </div>
            <div class="name">{{ obj.name }}</div>
          </div>
        </div>
      </div>

      <div class="input-container">
        <textarea
            v-model="inputText"
            :placeholder="'向' + currentChatObject.name + '提问...'"
            @keydown.enter.prevent="sendMessage"
            rows="1"
            @input="handleInput"
        ></textarea>
        <div class="action-buttons">
          <button class="action-button" title="清空对话" @click="clearMessages">
            <el-icon><Delete /></el-icon>
          </button>
        </div>
      </div>
      <button class="send-button" @click="sendMessage" :disabled="!isValidInput">
        <i class="fas fa-paper-plane"></i>
      </button>
    </div>
    <div class="input-warning">
      {{ inputWarning }}
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.chat-container {
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(90deg, #4e54c8, #8f94fb);
  color: white;
  padding: 10px;
  text-align: center;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  font-size: 1.8rem;
  margin-bottom: 5px;
}

.chat-header p {
  opacity: 0.9;
  font-size: 0.9rem;
}

.chat-status {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  padding: 5px 15px;
  border-radius: 8px;
  font-size: 0.85rem;
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #4ade80;
  margin-right: 8px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: #f9fafc;
}

.message {
  display: flex;
  max-width: 80%;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.ai {
  align-self: flex-start;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2rem;
  margin: 0 10px;
  flex-shrink: 0;
}

.ai .avatar {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.user .avatar {
  background: linear-gradient(135deg, #f093fb, #f5576c);
  color: white;
}

.message-content {
  background: white;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  position: relative;
}

.ai .message-content {
  background: #f0f4ff;
  border-top-left-radius: 4px;
}

.user .message-content {
  background: linear-gradient(135deg, #4e54c8, #8f94fb);
  color: white;
  border-top-right-radius: 4px;
}

.message-text {
  line-height: 1.5;
}

.message-time {
  font-size: 0.75rem;
  margin-top: 8px;
  opacity: 0.7;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 10px;
  background: white;
  border-top: 1px solid #eee;
  align-items: center;
}

.chat-object-selector {
  margin-right: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.chat-object-avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.4rem;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-object-avatar:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.chat-object-name {
  margin-top: 5px;
  font-size: 0.75rem;
  color: #666;
  text-align: center;
}

.chat-objects-dropdown {
  position: absolute;
  bottom: 70px;
  left: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  padding: 10px;
  width: 180px;
  z-index: 100;
  display: none;
  flex-direction: column;
  gap: 8px;
}

.chat-objects-dropdown.active {
  display: flex;
}

.chat-object-option {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
}

.chat-object-option:hover {
  background: #f5f7fb;
}

.chat-object-option.active {
  background: #f0f4ff;
}

.chat-object-option .avatar {
  width: 30px;
  height: 30px;
  font-size: 1rem;
  margin-right: 10px;
}

.chat-object-option .name {
  font-size: 0.9rem;
  font-weight: 500;
}

.input-container {
  flex: 1;
  display: flex;
  background: #f5f7fb;
  border-radius: 12px;
  padding: 5px;
  margin-right: 10px;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.input-container:focus-within {
  border-color: #4e54c8;
}

.chat-input textarea {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  padding: 12px 20px;
  resize: none;
  font-size: 1rem;
  max-height: 120px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  padding: 0 10px;
  align-items: center;
}

.action-button {
  background: none;
  border: none;
  color: #6c757d;
  font-size: 1.2rem;
  cursor: pointer;
  transition: color 0.2s;
}

.action-button:hover {
  color: #4e54c8;
}

.send-button {
  background: linear-gradient(135deg, #4e54c8, #8f94fb);
  color: white;
  border: none;
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2rem;
  cursor: pointer;
  transition: transform 0.2s;
  box-shadow: 0 4px 10px rgba(78, 84, 200, 0.3);
}

.send-button:hover {
  transform: scale(1.05);
}

.send-button:active {
  transform: scale(0.98);
}

.send-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background: #f0f4ff;
  border-radius: 12px;
  border-top-left-radius: 4px;
  max-width: 120px;
  margin-bottom: 10px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #8f94fb;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(1) { animation-delay: -0.32s; }
.typing-dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #6c757d;
  text-align: center;
  padding: 20px;
}

.empty-state i {
  font-size: 4rem;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-state h3 {
  font-size: 1.5rem;
  margin-bottom: 10px;
}

.empty-state p {
  max-width: 500px;
  line-height: 1.6;
}

.input-warning {
  color: #e74c3c;
  font-size: 0.8rem;
  text-align: center;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.message-sender {
  font-weight: 600;
  font-size: 0.9rem;
}

.ai .message-sender {
  color: #667eea;
}

.user .message-sender {
  color: #f5576c;
}
/* 让MdPreview背景透明，并继承父元素的字体颜色 */
:deep(.md-editor-preview) {
  background: transparent !important;
  color: inherit;
}

/* 调整预览内容中的代码块背景 */
:deep(.md-editor-preview code) {
  background: rgba(0, 0, 0, 0.1);
}

/* 用户消息中的代码块背景 */
.user :deep(.md-editor-preview code) {
  background: rgba(255, 255, 255, 0.2);
}
</style>